package com.itheima.admin.Service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.Service.AdUserService;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.model.common.admin.dtos.UserDto;
import com.itheima.model.common.admin.pojos.AdUser;
import com.itheima.model.common.dtos.ResponseResult;
import com.itheima.model.common.enums.AppHttpCodeEnum;
import com.itheima.utils.common.AppJwtUtil;
import org.assertj.core.util.Maps;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult login(UserDto userDto) {
        //判断用户名密码是否为空
        if (userDto.getName()==null||userDto.getPassword()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NAME_PASSWORD);
        }
        //校验用户名密码长度
        if (userDto.getName().length()>20||userDto.getPassword().length()>20){
            return ResponseResult.errorResult(AppHttpCodeEnum.TOO_LONG);
        }
        //判断密码是否正确
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",userDto.getName());
        List<AdUser> list = list(queryWrapper);
        if (list != null && list.size()==1){
            AdUser adUser = list.get(0);
            //密码加密
            String pswd = DigestUtils.md5DigestAsHex((userDto.getPassword() + adUser.getSalt()).getBytes());
            if (adUser.getPassword().equals(pswd)){
                //判断状态
                if (adUser.getStatus()==9){
                    //发送令牌
                    Map<String,Object> map = new HashMap<>();
                    adUser.setPassword("");
                    adUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                    map.put("user",adUser);
                    return ResponseResult.okResult(map);

                }else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.STATUSNO);
                }
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }

    }
}
